package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     * @param keyword
     * @param userId
     */
    @Override
    @Async //异步保存
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户搜索记录
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch userSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.存在,更新时间
        if (userSearch != null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
        }
        //3.不存在,判断数据量是否超过10
        query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by("createTime"));
        List<ApUserSearch> userSearches = mongoTemplate.find(query, ApUserSearch.class);
        userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());
        if (userSearches.size() < 10){
            //数量小于10,直接插入
            mongoTemplate.insert(userSearch);
        }else{
            //数量大于10
            String lastSearchId = userSearches.get(userSearches.size() - 1).getId();
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastSearchId)),userSearch );
        }

    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by("createTime")),
                ApUserSearch.class);
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 删除搜索历史
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if (historySearchDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        mongoTemplate.remove(Query.query(Criteria
                .where("userId").is(user.getId())
                .and("id").is(historySearchDto.getId())),ApUserSearch.class);
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
